package com.yan.token.service;

import java.security.Timestamp;
import java.util.Date;

/**
 * @author yanheng
 * @data 2019/12/11 10:25
 */
public class AuthToken {
    private static final long DEFAUTL_EXPIRED_TIME_INTERVAL = 1 * 60 * 90;
    private String token;
    private long createTime;
    private long expiredTimeInterval = DEFAUTL_EXPIRED_TIME_INTERVAL;

    public AuthToken(String token, long createTime){
        this.token = token;
        this.createTime = createTime;
    }

    public AuthToken(String token, long createTime, long expiredTimeInterval){
        this.token = token;
        this.createTime = createTime;
        this.expiredTimeInterval = expiredTimeInterval;
    }

    public static AuthToken generate(String originalUrl, String appId, String password, long timestamp){
        StringBuffer tokenBuf = new StringBuffer();
        tokenBuf.append(originalUrl).append("?appId=").append(appId)
                .append("&password").append(password)
                .append("&timestamp").append(timestamp);
        String token = String.valueOf(tokenBuf.toString().hashCode());
        return new AuthToken(token, timestamp);
    }

    public String getToken(){
        return token;
    }

    public long getCreateTime(){
        return createTime;
    }

    public boolean isExpired(){
        Long currentTime = System.currentTimeMillis();
        return (this.createTime + this.expiredTimeInterval) < currentTime;
    }

    public boolean match(AuthToken authToken){
        return this.token.equals(authToken.getToken());
    }

}
